package com.nondo.rdp.finance.service.impl.setting.advert;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.setting.advert.Advert;
import com.nondo.rdp.finance.repository.setting.advert.AdvertRepository;
import com.nondo.rdp.finance.service.setting.advert.AdvertService;

@Transactional
@Service
public class AdvertServiceImpl implements AdvertService {
    @Autowired
    AdvertRepository advertRepository;

    @Override
    public Advert findOne(Long id) {
        return this.advertRepository.findOne(id);
    }

    @Override
    public Advert save(Advert Advert) {
        return this.advertRepository.save(Advert);
    }

    @Override
    public void update(Advert Advert) {
        this.advertRepository.save(Advert);
    }

    @Override
    public void delete(Long id) {
        this.advertRepository.deleteById(id);
    }

    @Override
    public Page<Advert> findAll(Page<Advert> page, Advert advert) {
        Sort sort = new Sort(Sort.Direction.DESC, "sort");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Advert> dictPage = advertRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
			if (advert != null) {
	            //搜索ID
	            if (advert.getId() != null && advert.getId() != 0) {
	            	predicates.add(builder.equal(root.get("id"), advert.getId()));
	            }
	
	            //搜索内容
	            if (StringUtils.isNotEmpty(advert.getTitle())) {
	                predicates.add(builder.like(root.get("title"), "%" + advert.getTitle() + "%"));
	            }

                //搜索类型
                if (advert.getType() != null) {
                    predicates.add(builder.equal(root.get("type"), advert.getType()));
                }
            }

            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<Advert>(dictPage);
    }

	@Override
	public List<Advert> findAll(Integer type) {
		return advertRepository.findAll(type);
	}

}